<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>淡入淡出</title>
</head>

<body>
  <div id="fade-obj" style="width:300px;height:300px;background:#000;opacity:1;"></div>
  <button id="fade-btn">淡出</button>
  <script>
    const fadeBtn = document.getElementById("fade-btn")
    const fadeObj = document.getElementById("fade-obj");

    fadeBtn.state = 0// 0:淡出 1:淡入
    let timer

    fadeBtn.addEventListener("click", function () {
      fadeBtn.disabled = true
      if (fadeBtn.state === 0) {//处理淡出

        timer = setInterval(() => {
          fadeObj.style.opacity -= 0.01
          if (fadeObj.style.opacity <= 0) {
            clearInterval(timer)
            fadeBtn.disabled = false
            fadeBtn.innerHTML = '淡入'
            fadeBtn.state = 1
          }
        }, 10);

      } else {//处理淡入
        timer = setInterval(() => {
          fadeObj.style.opacity = parseFloat(fadeObj.style.opacity) + 0.01
          if (fadeObj.style.opacity >= 1) {
            clearInterval(timer)
            fadeBtn.disabled = false
            fadeBtn.innerHTML = '淡出'
            fadeBtn.state = 0
          }
        }, 10);
      }
    }, false);
  </script>
</body>

</html>